package com.session.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import com.iman.sumer.util.Web7Util;
import com.iman.common.util.ConfigUtil;
import com.iman.sumer.Web7Constants;
import com.iman.sumer.domain.SessionBean;
import com.iman.sumer.service.SharedSessionService;
import com.iman.sumer.util.HoldWebSpringContext;
import com.iman.sumer.util.Web7Util;

public class SessionFilter implements Filter {
	private String encoding;
	private  Logger logger = LoggerFactory.getLogger(SessionFilter.class);

	public SessionFilter() {
	}

	public void init(FilterConfig filterconfig) throws ServletException {
		encoding = "utf-8";
	}

	public void doFilter(ServletRequest servletrequest, 	ServletResponse servletresponse, FilterChain filterchain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) servletrequest;
		HttpSession session = req.getSession();
		HttpServletResponse resp = (HttpServletResponse) servletresponse;

		//获取所有的cookie
		Cookie[] cookies = req.getCookies();
		// yes   no   是否是测试环境
		String testEnv= ConfigUtil.getString( "testEnv");
		String teacherYN= ConfigUtil.getString( "testUserJiaoshi");
		/***************其他人可以使用这个  学生******************/
		String  uid = "";
		String  uidpk = "";
		if(testEnv!=null && testEnv.equalsIgnoreCase("yes")){
		     uid = "2148bb858f4eb9009db1bc0483a0b815";
		     uidpk = "4ad90b6264b15a1b6fc6d4ed05fab464";
		     /*********  教师*********/
			  if(teacherYN!=null && "Y".equalsIgnoreCase(teacherYN.trim())){
				     uid = "2cee4e45783ab872237939585870cf35";
				     uidpk = "e49c48ae3cbae47c0239edb156015d15";
			  }
		 }
	 	  
		if(cookies!=null)
		{
			for(Cookie c:cookies)
			{
				logger.info("cookie name="+c.getName()+"  cookie value:="+c.getValue()+"  all=:"+c.toString());
				if(Web7Constants.SHARECOOKIEUSERID .equals(c.getName() )){
					uid = c.getValue();
				}
				if(Web7Constants.SHARECOOKIEUSERID_PRIVATEKEY .equals(c.getName() )){
					uidpk = c.getValue();
				}
			}
		}
		
		 //TODO	如果   false 说明 失效，或者 错误，需要重新登陆
	  	 boolean  isRightCookie =   Web7Util.checkCookieIdIsOk(uid,uidpk);
	  	 logger.info("cookie nameuid="+uid+"  cookie uidpk:="+uidpk +"-----------》isRightCookie  result =:"+isRightCookie );
		 SessionBean sessionBean = new   SessionBean();
		 //  redis 中缓存的KEY SessionBean.USER_SESSION_KEY_PERFIX+sessionkey,  SessionBean.USER_SESSION_SUBKEY_SESSION
		 sessionBean = (SessionBean)session.getAttribute(SessionBean.USER_SESSION_KEY_PERFIX+SessionBean.USER_SESSION_SUBKEY_SESSION );
		 //当前容器不存在 ，
	     if(sessionBean == null ){
	    	//容器缓存失效
	    	try{
				SharedSessionService sessionUtil =	 	HoldWebSpringContext.getBean("shareusersession", SharedSessionService.class);
				sessionBean = sessionUtil.getSeesion(uid);
			}catch(Exception e){
			  logger.error(e.getMessage(),e);
			}
	     }
	 
		//最后验证是否真的失效
	 	String[] nocheckURL = {"/sumer/share/mainShare" ,"/sumer/course/mainCourse" ,"teamgroup/getHeadImg"};
	 	String path = ((HttpServletRequest)servletrequest).getRequestURI();
		if (sessionBean == null ) {
			 boolean  relogin = true;
			for(String url :nocheckURL){
				if(url == null || path.indexOf(  url)>=0 ){
					relogin = false;
					break;
				}
			}
			if(relogin){
				 logger.error("重新登录" );
			  	 ((HttpServletResponse)servletresponse).sendRedirect(ConfigUtil.getString( "notLogin" ) );
			  	 return;
			}
		  	
		}else{
			//放入内部session 数据量
		    session.setAttribute(SessionBean.USER_SESSION_KEY_PERFIX+SessionBean.USER_SESSION_SUBKEY_SESSION ,sessionBean );
		    logger.info("放入本地session"+ SessionBean.USER_SESSION_KEY_PERFIX+SessionBean.USER_SESSION_SUBKEY_SESSION +"--->"+sessionBean);
		}
		
		filterchain.doFilter(servletrequest, servletresponse);
	}

	public void destroy() {

	}
}